package cn.xiaolang.function.network.multiplexing;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author Dean
 * @date 2022-02-13
 */
public class Acceptor implements Runnable {

    private final ServerSocketChannel ssc;

    private final Selector selector;

    public Acceptor(Selector selector, ServerSocketChannel ssc) {
        this.ssc = ssc;
        this.selector = selector;

    }

    @Override
    public void run() {
        try {
            // 接收client的连接
            SocketChannel sc = ssc.accept();
            if (sc != null) {
                System.out.println(sc.socket().getRemoteSocketAddress().toString() + " connected! ");
                // NON BLOCKING
                sc.configureBlocking(false);
                // 向selector注册一个OP_READ事件，然后返回该通道的key
                SelectionKey sk = sc.register(selector, SelectionKey.OP_READ);
                // 使一个阻塞住的selector操作立即返回
                selector.wakeup();
                // 给定key一个附加的TCPHandler对象
                sk.attach(new TCPHandler(sk, sc));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

